﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using EncryptionLib.Users;
using EncryptionLib;
using System.Security.Cryptography;
using EncryptionLib.Encryption;
using EncryptionLib.Signature;



namespace TotalCommander_v3
{

    public partial class frmMain : Form, System.Collections.IComparer
    {
        public static IUserManager m_userManager = null;

        public static string sEmail = string.Empty;
        public static string sPassphrase = string.Empty;

        SymmetricAlgorithms SymmetricAlgorithms = SymmetricAlgorithms.DES;
        CipherMode CipherMode = CipherMode.ECB;
        PaddingMode PaddingMode = PaddingMode.PKCS7;
        bool Zip = true;


        public const string sENP = ".enp";
        public const string sSIG = ".sig";
        public frmMain()
        {
            InitializeComponent();
        }

        private int m_SortColumnLeft = -1;
        private SortOrder m_SortOrderLeft = SortOrder.None;
        private int m_SortColumnRight = -1;
        private SortOrder m_sortOrderRight = SortOrder.None;
        private bool m_bFag = true;
        private int m_iControlLeft = 1;
        private int m_iControlRight = 1;

        private int m_iIndexLeft = 0;
        private int m_iIndexRight = 0;
        private int m_iParentLeft = 0;
        private int m_iParentRight = 0;

        private IList<ListViewItem> m_LeftList = new List<ListViewItem>();
        private IList<ListViewItem> m_RightList = new List<ListViewItem>();
        private DriveInfo[] m_arrDrives = DriveInfo.GetDrives();

        public static string userPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\users.xml";

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                m_userManager = new UserManagerXML(userPath);
            }
            catch (Exception)
            {

            }

            //
            this.updateMenu(false);

            // vong lap add cac o dia vao toolStrip
            foreach (DriveInfo drive in m_arrDrives)
            {
                if (drive.IsReady)
                {
                    toolStripComboBoxLeft.Items.Add(drive.Name);
                    toolStripComboBoxRight.Items.Add(drive.Name);
                }
            }

            if (toolStripComboBoxLeft.Items.Count > 0)
                toolStripComboBoxLeft.SelectedIndex = 0;
            else
                displayDirectory(@"C:\", listViewLeft, imageListLeft, m_iIndexLeft, txtPathLeft, toolStripStatusLabelLeft);
            if (toolStripComboBoxRight.Items.Count > 0)
                toolStripComboBoxRight.SelectedIndex = 0;
            else
                displayDirectory(@"C:\", listViewRight, imageListRight, m_iIndexRight, txtPathRight, toolStripStatusLabelRight);

            txtPathLeft.Text = m_arrDrives[0].Name.ToString();
            txtPathRight.Text = m_arrDrives[0].Name.ToString();

            toolStripStatusLabelLeft.Text = countSub(new DirectoryInfo(@"C:\"));
            toolStripStatusLabelRight.Text = countSub(new DirectoryInfo(@"C:\"));

            listViewLeft.Items[0].Focused = true;
            listViewLeft.Items[0].Selected = true;


            this.labelLogin.Text = "Login";
            this.labelName.Text = String.Empty;
            this.labelUserSetting.Visible = false;
            this.labelNewUser.Visible = true;
            this.settingToolStripMenuItem.Enabled = false;

            // 
            this.encryptToolStripMenuItem.Enabled = false;
            this.encryptWithToolStripMenuItem1.Enabled = false;

        }

        // ham nay dung de hien cac file, folder con
        private void displayDirectory(string sPath, ListView listView, ImageList imageList, int iIndex, TextBox textBox, ToolStripStatusLabel toolStripStatusLabel)
        {
            try
            {
                iIndex = 0;
                imageList.Images.Clear();


                ListViewItem lwItem;
                ListViewItem.ListViewSubItem lwSubDirItem;
                ListViewItem.ListViewSubItem lwSubFileItem;

                DirectoryInfo directory = new DirectoryInfo(sPath);
                DirectoryInfo[] arrDirectories = directory.GetDirectories();
                FileInfo[] arrFiles = directory.GetFiles();

                IntPtr hImgSmall; //the handle to the system image list
                SHFILEINFO shinfo = new SHFILEINFO();

                listView.View = View.Details;
                listView.Items.Clear();

                listView.BeginUpdate();
                listView.SmallImageList = imageList;

                if (checkStatusOfPath(sPath) == 0)
                {
                    //MessageBox.Show("Khong La o dia");
                    lwItem = new ListViewItem();
                    lwItem.Text = "[...]";

                    System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
                    imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListLeft.ImageStream")));
                    imageList.TransparentColor = System.Drawing.Color.Transparent;
                    imageList.Images.SetKeyName(0, "ImagineSimple.bmp");

                    lwItem.ImageIndex = iIndex++;

                    lwSubDirItem = new ListViewItem.ListViewSubItem();
                    lwSubDirItem.Text = " ";
                    lwItem.SubItems.Add(lwSubDirItem);

                    lwSubDirItem = new ListViewItem.ListViewSubItem();
                    lwSubDirItem.Text = "Dir";
                    lwItem.SubItems.Add(lwSubDirItem);

                    lwSubDirItem = new ListViewItem.ListViewSubItem();
                    lwSubDirItem.Text = directory.CreationTime.ToString();
                    lwItem.SubItems.Add(lwSubDirItem);

                    listView.Items.Add(lwItem);
                }

                foreach (DirectoryInfo dir in arrDirectories)
                {
                    lwItem = new ListViewItem();
                    lwItem.Text = dir.Name.ToString();
                    lwItem.Tag = dir.FullName;

                    try
                    {
                        hImgSmall = Win32.SHGetFileInfo(dir.FullName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);
                        System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);

                        lwItem.ImageIndex = iIndex++;

                        lwSubDirItem = new ListViewItem.ListViewSubItem();
                        lwSubDirItem.Text = " ";
                        lwItem.SubItems.Add(lwSubDirItem);

                        lwSubDirItem = new ListViewItem.ListViewSubItem();
                        lwSubDirItem.Text = "Dir";
                        lwItem.SubItems.Add(lwSubDirItem);

                        lwSubDirItem = new ListViewItem.ListViewSubItem();
                        lwSubDirItem.Text = dir.CreationTime.ToString();
                        lwItem.SubItems.Add(lwSubDirItem);

                        imageList.Images.Add(myIcon);

                        listView.Items.Add(lwItem);
                    }

                    catch (Exception)
                    {
                        listView.Items.Add(dir.FullName);
                    }
                }

                foreach (FileInfo file in arrFiles)
                {
                    lwItem = new ListViewItem();
                    lwItem.Text = file.Name.ToString();
                    lwItem.Tag = file.FullName;

                    try
                    {
                        hImgSmall = Win32.SHGetFileInfo(file.FullName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);
                        System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);

                        lwItem.ImageIndex = iIndex++;

                        lwSubFileItem = new ListViewItem.ListViewSubItem();
                        lwSubFileItem.Text = (file.Length / 1024).ToString() + " K";
                        lwItem.SubItems.Add(lwSubFileItem);

                        lwSubFileItem = new ListViewItem.ListViewSubItem();
                        lwSubFileItem.Text = " ";
                        lwItem.SubItems.Add(lwSubFileItem);

                        lwSubFileItem = new ListViewItem.ListViewSubItem();
                        lwSubFileItem.Text = file.CreationTime.ToString();
                        lwItem.SubItems.Add(lwSubFileItem);

                        imageList.Images.Add(myIcon);
                        listView.Items.Add(lwItem);
                    }
                    catch (Exception)
                    {
                        listView.Items.Add(file.FullName);
                    }


                }
                listView.EndUpdate();

                textBox.Text = sPath.ToString();
                toolStripStatusLabel.Text = countSub(new DirectoryInfo(textBox.Text));

            }
            catch (System.UnauthorizedAccessException)
            {
                MessageBox.Show("Access deny", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.Exception error)
            {
                MessageBox.Show(error.GetType().FullName);
                MessageBox.Show("Error: " + error.Message + " :" + error.StackTrace);
            }

        }

        private void toolStripComboBoxLeft_SelectedIndexChanged(object sender, EventArgs e)
        {
            displayDirectory(@toolStripComboBoxLeft.Text.ToString(), listViewLeft, imageListLeft, m_iIndexLeft, txtPathLeft, toolStripStatusLabelLeft);

            if (m_LeftList.Count != 0)
                m_LeftList.Clear();

            listViewLeft.Focus();
            listViewLeft.Items[0].Focused = true;
            listViewLeft.Items[0].Selected = true;
        }

        private void toolStripComboBoxRight_SelectedIndexChanged(object sender, EventArgs e)
        {
            displayDirectory(@toolStripComboBoxRight.Text.ToString(), listViewRight, imageListRight, m_iIndexRight, txtPathRight, toolStripStatusLabelRight);

            if (m_RightList.Count != 0)
                m_RightList.Clear();

            listViewRight.Focus();
            listViewRight.Items[0].Focused = true;
            listViewRight.Items[0].Selected = true;
        }

        private void listViewLeft_DoubleClick(object sender, EventArgs e)
        {
            ListViewItem item = listViewLeft.FocusedItem;
            if (item == null)
                return;
            if (item.SubItems[2].Text == "Dir")
            {
                if (checkStatusOfPath(listViewLeft.SelectedItems[0].Text) == 1)
                {
                    DirectoryInfo dir = Directory.GetParent(txtPathLeft.Text);
                    displayDirectory(dir.FullName, listViewLeft, imageListLeft, m_iIndexLeft, txtPathLeft, toolStripStatusLabelLeft);

                    listViewLeft.Items[m_iParentLeft].Focused = true;
                    listViewLeft.Items[m_iParentLeft].Selected = true;
                }
                else
                {
                    m_iParentLeft = listViewLeft.SelectedIndices[0];

                    txtPathLeft.Text = listViewLeft.SelectedItems[0].Tag.ToString();
                    displayDirectory(txtPathLeft.Text, listViewLeft, imageListLeft, m_iIndexLeft, txtPathLeft, toolStripStatusLabelLeft);

                    listViewLeft.Items[0].Focused = true;
                    listViewLeft.Items[0].Selected = true;
                }
            }
            else
                System.Diagnostics.Process.Start(Path.Combine(txtPathLeft.Text, item.SubItems[0].Text));
        }

        private void listViewRight_DoubleClick(object sender, EventArgs e)
        {
            ListViewItem item = listViewRight.FocusedItem;
            if (item == null)
                return;
            if (item.SubItems[2].Text == "Dir")
            {
                if (checkStatusOfPath(listViewRight.SelectedItems[0].Text) == 1)
                {
                    DirectoryInfo dir = Directory.GetParent(txtPathRight.Text);
                    displayDirectory(dir.FullName, listViewRight, imageListRight, m_iIndexRight, txtPathRight, toolStripStatusLabelRight);

                    listViewRight.Items[m_iParentRight].Focused = true;
                    listViewRight.Items[m_iParentRight].Selected = true;
                }
                else
                {
                    m_iParentRight = listViewRight.SelectedIndices[0];

                    txtPathRight.Text = listViewRight.SelectedItems[0].Tag.ToString();
                    displayDirectory(txtPathRight.Text, listViewRight, imageListRight, m_iIndexRight, txtPathRight, toolStripStatusLabelRight);

                    listViewRight.Items[0].Focused = true;
                    listViewRight.Items[0].Selected = true;
                }
            }
            else
            {
                System.Diagnostics.Process.Start(Path.Combine(txtPathRight.Text, item.SubItems[0].Text));
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct SHFILEINFO
        {
            public IntPtr hIcon;
            public IntPtr iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        };

        public class Win32
        {
            public const uint SHGFI_ICON = 0x100;
            public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
            public const uint SHGFI_SMALLICON = 0x1; // 'Small icon

            [DllImport("shell32.dll")]
            public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
        }

        private int checkStatusOfPath(string sPath)
        {
            if (sPath == "[...]")
                return 1;
            else
            {
                foreach (DriveInfo drive in m_arrDrives)
                {
                    if (drive.IsReady)
                        if (sPath == drive.Name)
                            return 2;
                }
            }

            return 0;
        }

        // xap xep listView ben trai
        private void listViewLeft_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (e.Column != m_SortColumnLeft)
            {
                m_SortColumnLeft = e.Column;
                m_SortOrderLeft = SortOrder.Ascending;
            }
            else
            {
                if (m_SortOrderLeft == SortOrder.Ascending)
                    m_SortOrderLeft = SortOrder.Descending;
                else
                    m_SortOrderLeft = SortOrder.Ascending;
            }

            System.Collections.IComparer temp = listViewLeft.ListViewItemSorter;
            this.listViewLeft.ListViewItemSorter = new ListViewItemComparer(e.Column, m_SortOrderLeft);
            listViewLeft.Sort();
            this.listViewLeft.ListViewItemSorter = temp;

            return;
        }

        // xap xep listView ben phai
        private void listViewRight_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (e.Column != m_SortColumnRight)
            {
                m_SortColumnRight = e.Column;
                m_sortOrderRight = SortOrder.Ascending;
            }
            else
            {
                if (m_sortOrderRight == SortOrder.Ascending)
                    m_sortOrderRight = SortOrder.Descending;
                else
                    m_sortOrderRight = SortOrder.Ascending;
            }


            System.Collections.IComparer temp = listViewRight.ListViewItemSorter;
            this.listViewRight.ListViewItemSorter = new ListViewItemComparer(e.Column, m_sortOrderRight);
            listViewRight.Sort();
            this.listViewRight.ListViewItemSorter = temp;

        }


        #region IComparer Members

        int System.Collections.IComparer.Compare(object x, object y)
        {
            //throw new NotImplementedException();
            DirectoryInfo dix = (DirectoryInfo)x;
            DirectoryInfo diy = (DirectoryInfo)y;
            return -string.Compare(dix.FullName, diy.FullName);

        }

        #endregion

        private void listViewRight_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.Control == true && e.KeyCode == Keys.A && e.Shift == false && e.Alt == false)
            {
                //int iTemp = 0;
                foreach (ListViewItem item in listViewRight.Items)
                {
                    if (item.ForeColor == Color.Red)
                    {
                        item.ForeColor = Color.Black;
                        m_iControlRight = 1;
                    }
                    else
                    {
                        item.ForeColor = Color.Red;
                        m_iControlRight = 0;
                        m_RightList.Add(item);
                    }
                }
                if (m_iControlRight == 1)
                    m_RightList.Clear();

                return;
            }

            if (e.KeyCode == Keys.F6 && e.Shift == false && e.Control == false && e.Alt == false)
            {
                moveFromRightToLeft();
                return;
            }

            if (e.KeyCode == Keys.F5 && e.Shift == false && e.Control == false && e.Alt == false)
            {
                copyFromRightToLeft();
                return;
            }

            if (e.KeyCode == Keys.F8 && e.Shift == false && e.Control == false && e.Alt == false)
            {
                deleteFromRight();
                return;
            }


            if (e.KeyCode == Keys.F7 && e.Shift == false && e.Control == false && e.Alt == false)
            {
                createFromRight();
                return;
            }


            if (e.Shift == true && e.KeyCode == Keys.F6 && e.Alt == false && e.Control == false)
            {
                renameFromRight();
                return;
            }

            if (e.KeyCode == Keys.Insert && e.Shift == false && e.Control == false && e.Alt == false)
            {
                ListView.SelectedListViewItemCollection items = this.listViewRight.SelectedItems;

                foreach (ListViewItem item in items)
                {
                    if (item.Focused == true)
                    {
                        if (item.ForeColor == Color.Red)
                            item.ForeColor = Color.Black;
                        else
                            item.ForeColor = Color.Red;
                    }
                }

                ListViewItem i = listViewRight.FocusedItem;
                int pos = listViewRight.Items.IndexOf(i);
                if (pos < listViewRight.Items.Count - 1)
                {
                    listViewRight.SelectedIndices.Add(pos + 1);
                    listViewRight.Items[pos + 1].Focused = true;
                }
                else
                    pos -= 1;

                if (i != null)
                    m_RightList.Add(i);
                return;
            }

            if (e.KeyCode == Keys.Back && e.Shift == false && e.Control == false && e.Alt == false)
            {
                if (checkStatusOfPath(txtPathRight.Text) == 0)
                {
                    DirectoryInfo dir = Directory.GetParent(txtPathRight.Text);
                    displayDirectory(dir.FullName, listViewRight, imageListRight, m_iIndexRight, txtPathRight, toolStripStatusLabelRight);
                }

                if (m_LeftList.Count != 0)
                    m_LeftList.Clear();

                listViewRight.Items[m_iParentRight].Focused = true;
                listViewRight.Items[m_iParentRight].Selected = true;
                return;
            }

            if (e.KeyCode == Keys.Enter && e.Shift == false && e.Control == false && e.Alt == false)
            {
                ListViewItem item = listViewRight.FocusedItem;
                if (item == null)
                    return;
                if (item.SubItems[2].Text == "Dir")
                {
                    if (listViewRight.SelectedItems.Count > 0)
                    {
                        if (checkStatusOfPath(listViewRight.SelectedItems[0].Text) == 1)
                        {
                            DirectoryInfo dir = Directory.GetParent(txtPathRight.Text);
                            displayDirectory(dir.FullName, listViewRight, imageListRight, m_iIndexRight, txtPathRight, toolStripStatusLabelRight);

                            listViewRight.Items[m_iParentRight].Focused = true;
                            listViewRight.Items[m_iParentRight].Selected = true;
                        }
                        else
                        {
                            m_iParentRight = listViewRight.SelectedIndices[0];

                            txtPathRight.Text = listViewRight.SelectedItems[0].Tag.ToString();
                            displayDirectory(txtPathRight.Text, listViewRight, imageListRight, m_iIndexRight, txtPathRight, toolStripStatusLabelRight);

                            listViewRight.Items[0].Focused = true;
                            listViewRight.Items[0].Selected = true;
                        }
                    }
                }
                else
                    System.Diagnostics.Process.Start(Path.Combine(txtPathRight.Text, item.SubItems[0].Text));

                if (m_RightList.Count != 0)
                    m_RightList.Clear();
                return;
            }

            if (e.KeyCode == Keys.Space && e.Shift == false && e.Control == false && e.Alt == false)
            {
                try
                {
                    ListViewItem item = listViewRight.FocusedItem;
                    if (item.SubItems[2].Text == "Dir")
                    {
                        item.SubItems[2].Text = countSize(new DirectoryInfo(Path.Combine(txtPathRight.Text, item.SubItems[0].Text))).ToString();
                        m_RightList.Add(item);
                    }
                }
                catch (System.UnauthorizedAccessException)
                {
                    MessageBox.Show("Access deny", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    displayDirectory(txtPathRight.Text, listViewRight, imageListRight, m_iIndexRight, txtPathRight, toolStripStatusLabelRight);
                }
                return;
            }



            if (e.Control == true && e.KeyCode == Keys.Oem5 && e.Alt == false && e.Shift == false)
            {
                txtPathRight.Text = toolStripComboBoxRight.Text;
                displayDirectory(toolStripComboBoxRight.Text, listViewRight, imageListRight, m_iIndexRight, txtPathRight, toolStripStatusLabelRight);

                listViewRight.Items[0].Focused = true;
                listViewRight.Items[0].Selected = true;

                if (m_RightList.Count != 0)
                    m_RightList.Clear();

                return;
            }
        }

        private void listViewLeft_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F6 && e.Shift == false && e.Control == false && e.Alt == false)
            {
                moveFromLeftToRight();
                return;
            }

            if (e.KeyCode == Keys.F5 && e.Shift == false && e.Control == false && e.Alt == false)
            {
                copyFromLefttToRight();
                return;
            }

            if (e.KeyCode == Keys.F8 && e.Shift == false && e.Control == false && e.Alt == false)
            {
                deleteFromLeft();
                return;
            }

            if (e.KeyCode == Keys.F7 && e.Shift == false && e.Control == false && e.Alt == false)
            {
                createFromLeft();
                return;
            }

            if (e.Shift == true && e.KeyCode == Keys.F6 && e.Control == false && e.Alt == false)
            {
                renameFromLeft();

                return;
            }

            if (e.KeyCode == Keys.Insert && e.Shift == false && e.Control == false && e.Alt == false)
            {
                ListView.SelectedListViewItemCollection items = this.listViewLeft.SelectedItems;
                foreach (ListViewItem item in items)
                {

                    if (item.Focused == true)
                    {
                        if (item.ForeColor == Color.Red)
                            item.ForeColor = Color.Black;
                        else
                            item.ForeColor = Color.Red;
                    }
                }

                ListViewItem i = listViewLeft.FocusedItem;
                int pos = listViewLeft.Items.IndexOf(i);
                if (pos < listViewLeft.Items.Count - 1)
                {
                    listViewLeft.SelectedIndices.Add(pos + 1);
                    listViewLeft.Items[pos + 1].Focused = true;
                }
                else
                    pos -= 1;
                if (i != null)
                    m_LeftList.Add(i);
                return;
            }

            if (e.KeyCode == Keys.Back && e.Shift == false && e.Control == false && e.Alt == false)
            {
                if (checkStatusOfPath(txtPathLeft.Text) == 0)
                {
                    DirectoryInfo dir = Directory.GetParent(txtPathLeft.Text);
                    displayDirectory(dir.FullName, listViewLeft, imageListLeft, m_iIndexLeft, txtPathLeft, toolStripStatusLabelLeft);
                }


                if (m_LeftList.Count != 0)
                    m_LeftList.Clear();

                listViewLeft.Items[m_iParentLeft].Focused = true;
                listViewLeft.Items[m_iParentLeft].Selected = true;
                return;
            }


            if (e.KeyCode == Keys.Enter && e.Shift == false && e.Control == false && e.Alt == false)
            {

                ListViewItem item = listViewLeft.FocusedItem;
                if (item.SubItems[2].Text == "Dir")
                {
                    if (listViewLeft.SelectedItems.Count > 0)
                    {

                        if (checkStatusOfPath(listViewLeft.SelectedItems[0].Text) == 1)
                        {
                            DirectoryInfo dir = Directory.GetParent(txtPathLeft.Text);
                            displayDirectory(dir.FullName, listViewLeft, imageListLeft, m_iIndexLeft, txtPathLeft, toolStripStatusLabelLeft);

                            listViewLeft.Items[m_iParentLeft].Focused = true;
                            listViewLeft.Items[m_iParentLeft].Selected = true;
                        }
                        else
                        {
                            m_iParentLeft = listViewLeft.SelectedIndices[0];

                            txtPathLeft.Text = listViewLeft.SelectedItems[0].Tag.ToString();
                            displayDirectory(txtPathLeft.Text, listViewLeft, imageListLeft, m_iIndexLeft, txtPathLeft, toolStripStatusLabelLeft);

                            listViewLeft.Items[0].Focused = true;
                            listViewLeft.Items[0].Selected = true;
                        }
                    }
                }
                else
                {
                    System.Diagnostics.Process.Start(Path.Combine(txtPathLeft.Text, item.SubItems[0].Text));
                }

                if (m_LeftList.Count != 0)
                    m_LeftList.Clear();
                return;
            }

            if (e.KeyCode == Keys.Space && e.Shift == false && e.Control == false && e.Alt == false)
            {
                try
                {
                    ListViewItem item = listViewLeft.FocusedItem;
                    if (item.SubItems[2].Text == "Dir")
                    {
                        item.SubItems[2].Text = countSize(new DirectoryInfo(Path.Combine(txtPathLeft.Text, item.SubItems[0].Text))).ToString();
                        m_LeftList.Add(item);
                    }
                }
                catch (System.UnauthorizedAccessException)
                {
                    MessageBox.Show("Access deny", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    displayDirectory(txtPathLeft.Text, listViewLeft, imageListLeft, m_iIndexLeft, txtPathLeft, toolStripStatusLabelLeft);
                }
                return;
            }



            if (e.Control == true && e.KeyCode == Keys.Oem5)
            {
                txtPathLeft.Text = toolStripComboBoxLeft.Text;
                displayDirectory(toolStripComboBoxLeft.Text, listViewLeft, imageListLeft, m_iIndexLeft, txtPathLeft, toolStripStatusLabelLeft);

                listViewLeft.Items[0].Focused = true;
                listViewLeft.Items[0].Selected = true;

                if (m_LeftList.Count != 0)
                    m_LeftList.Clear();
                return;
            }

            if (e.Control == true && e.KeyCode == Keys.A && e.Shift == false && e.Alt == false)
            {

                foreach (ListViewItem item in listViewLeft.Items)
                {
                    if (item.ForeColor == Color.Red)
                    {
                        item.ForeColor = Color.Black;
                        m_iControlLeft = 1;
                    }
                    else
                    {
                        item.ForeColor = Color.Red;
                        m_iControlLeft = 0;
                        m_LeftList.Add(item);
                    }
                }
                if (m_iControlLeft == 1)
                    m_LeftList.Clear();
                return;
            }

        }
        // ==================================================================================

        private void moveFromRightToLeft()
        {
            m_iParentRight = listViewRight.SelectedIndices[0];

            if (m_RightList.Count == 0)
            {
                string strSource = Path.Combine(txtPathRight.Text, listViewRight.SelectedItems[0].Text);
                string strDestination = Path.Combine(txtPathLeft.Text, listViewRight.SelectedItems[0].Text);

                if (listViewRight.FocusedItem.SubItems[2].Text == "Dir")
                {
                    moveFolder(strSource, strDestination);
                    setStatus(m_iParentRight, listViewRight);
                }
                else
                {
                    moveFile(strSource, strDestination);
                    setStatus(m_iParentRight, listViewRight);
                }
            }
            // list co nhieu phan tu
            else
            {
                foreach (ListViewItem item in m_RightList)
                {
                    string strSource = Path.Combine(txtPathRight.Text, item.SubItems[0].Text);
                    string strDestination = Path.Combine(txtPathLeft.Text, item.SubItems[0].Text);

                    if (item.SubItems[2].Text == "Dir")
                    {
                        moveFolder(strSource, strDestination);
                        m_iParentRight--;
                    }
                    else
                    {
                        moveFile(strSource, strDestination);
                        m_iParentRight--;
                    }
                }

                setStatus(m_iParentRight, listViewRight);
                m_RightList.Clear();
            }
        }
        private void copyFromRightToLeft()
        {

            m_iParentRight = listViewRight.SelectedIndices[0];

            if (m_RightList.Count == 0)
            {
                string strSource = Path.Combine(txtPathRight.Text, listViewRight.SelectedItems[0].Text);
                string strDestination = Path.Combine(txtPathLeft.Text, listViewRight.SelectedItems[0].Text);
                if (listViewRight.FocusedItem.SubItems[2].Text == "Dir")
                {
                    copyFolder(strSource, strDestination);
                    setStatus(m_iParentRight, listViewRight);
                }
                else
                {
                    copyFile(strSource, strDestination);
                    setStatus(m_iParentRight, listViewRight);
                }
            }
            else
            {
                foreach (ListViewItem item in m_RightList)
                {
                    string strSource = Path.Combine(txtPathRight.Text, item.SubItems[0].Text);
                    string strDestination = Path.Combine(txtPathLeft.Text, item.SubItems[0].Text);
                    if (item.SubItems[2].Text == "Dir")
                        copyFolder(strSource, strDestination);
                    else
                        copyFile(strSource, strDestination);
                }

                setStatus(m_iParentRight, listViewRight);
                m_RightList.Clear();
            }
        }
        private void deleteFromRight()
        {
            m_iParentRight = listViewRight.SelectedIndices[0];

            if (m_RightList.Count == 0)
            {
                DialogResult mbb = MessageBox.Show("Are you sure to delete?", "Confirmation", MessageBoxButtons.YesNo);
                if (mbb == DialogResult.Yes)
                {
                    if (listViewRight.FocusedItem.SubItems[2].Text == "Dir")
                    {
                        if (listViewRight.SelectedItems[0].Text != "[...]")
                        {
                            deleteDirectory(new DirectoryInfo(Path.Combine(txtPathRight.Text, listViewRight.SelectedItems[0].Text)));
                            setStatus(m_iParentRight, listViewRight);
                        }
                    }
                    else
                    {
                        deleteFile(Path.Combine(txtPathRight.Text, listViewRight.SelectedItems[0].Text));
                        setStatus(m_iParentRight, listViewRight);
                    }
                }
            }
            else
            {
                DialogResult mbb = MessageBox.Show("Are you sure to delete all file and folder?", "Confirmation", MessageBoxButtons.YesNo);
                if (mbb == DialogResult.Yes)
                {
                    foreach (ListViewItem item in m_RightList)
                    {
                        if (item.SubItems[2].Text == "Dir")
                        {
                            if (item.SubItems[0].Text != "[...]")
                            {
                                deleteDirectory(new DirectoryInfo(Path.Combine(txtPathRight.Text, item.SubItems[0].Text)));
                                m_iParentRight--;
                            }
                        }
                        else
                        {
                            deleteFile(Path.Combine(txtPathRight.Text, item.SubItems[0].Text));
                            m_iParentRight--;
                        }
                    }

                    setStatus(m_iParentRight, listViewRight);
                    m_RightList.Clear();
                }
            }
        }
        private void createFromRight()
        {
            createDirectory(m_iParentRight, listViewRight, txtPathRight);
            if (m_RightList.Count != 0)
                m_RightList.Clear();
        }
        private void renameFromRight()
        {
            rename(m_iParentRight, listViewRight, txtPathRight);
            if (m_RightList.Count != 0)
                m_RightList.Clear();
        }


        private void moveFromLeftToRight()
        {

            m_iParentLeft = listViewLeft.SelectedIndices[0];

            if (m_LeftList.Count == 0)
            {
                string strSource = Path.Combine(txtPathLeft.Text, listViewLeft.SelectedItems[0].Text);
                string strDestination = Path.Combine(txtPathRight.Text, listViewLeft.SelectedItems[0].Text);

                if (listViewLeft.FocusedItem.SubItems[2].Text == "Dir")
                {
                    moveFolder(strSource, strDestination);
                    setStatus(m_iParentLeft, listViewLeft);
                }
                else
                {
                    moveFile(strSource, strDestination);
                    setStatus(m_iParentLeft, listViewLeft);
                }
            }

            else
            {
                foreach (ListViewItem item in m_LeftList)
                {
                    string strSource = Path.Combine(txtPathLeft.Text, item.SubItems[0].Text);
                    string strDestination = Path.Combine(txtPathRight.Text, item.SubItems[0].Text);

                    if (item.SubItems[2].Text == "Dir")
                    {
                        moveFolder(strSource, strDestination);
                        m_iParentLeft--;
                    }
                    else
                    {
                        moveFile(strSource, strDestination);
                        m_iParentLeft--;
                    }
                }
                setStatus(m_iParentLeft, listViewLeft);
                m_LeftList.Clear();
            }

        }
        private void copyFromLefttToRight()
        {

            m_iParentLeft = listViewLeft.SelectedIndices[0];

            if (m_LeftList.Count == 0)
            {
                string strSource = Path.Combine(txtPathLeft.Text, listViewLeft.SelectedItems[0].Text);
                string strDestination = Path.Combine(txtPathRight.Text, listViewLeft.SelectedItems[0].Text);
                if (listViewLeft.FocusedItem.SubItems[2].Text == "Dir")
                {
                    copyFolder(strSource, strDestination);
                    setStatus(m_iParentLeft, listViewLeft);
                }
                else
                {
                    copyFile(strSource, strDestination);
                    setStatus(m_iParentLeft, listViewLeft);
                }
            }
            else
            {
                foreach (ListViewItem item in m_LeftList)
                {
                    string strSource = Path.Combine(txtPathLeft.Text, item.SubItems[0].Text);
                    string strDestination = Path.Combine(txtPathRight.Text, item.SubItems[0].Text);
                    if (item.SubItems[2].Text == "Dir")
                        copyFolder(strSource, strDestination);
                    else
                        copyFile(strSource, strDestination);
                }

                setStatus(m_iParentLeft, listViewLeft);
                m_LeftList.Clear();
            }

        }
        private void deleteFromLeft()
        {

            m_iParentLeft = listViewLeft.SelectedIndices[0];

            if (m_LeftList.Count == 0)
            {
                DialogResult mbb = MessageBox.Show("Are you sure to delete?", "Confirmation", MessageBoxButtons.YesNo);
                if (mbb == DialogResult.Yes)
                {
                    if (listViewLeft.FocusedItem.SubItems[2].Text == "Dir")
                    {
                        if (listViewLeft.SelectedItems[0].Text != "[...]")
                        {
                            deleteDirectory(new DirectoryInfo(Path.Combine(txtPathLeft.Text, listViewLeft.SelectedItems[0].Text)));
                            setStatus(m_iParentLeft, listViewLeft);
                        }
                    }
                    else
                    {
                        deleteFile(Path.Combine(txtPathLeft.Text, listViewLeft.SelectedItems[0].Text));
                        setStatus(m_iParentLeft, listViewLeft);
                    }
                }
            }
            else
            {
                DialogResult mbb = MessageBox.Show("Are you sure to delete all file and folder?", "Confirmation", MessageBoxButtons.YesNo);
                if (mbb == DialogResult.Yes)
                {
                    foreach (ListViewItem item in m_LeftList)
                    {
                        if (item.SubItems[2].Text == "Dir")
                        {
                            if (item.SubItems[0].Text != "[...]")
                            {
                                deleteDirectory(new DirectoryInfo(Path.Combine(txtPathLeft.Text, item.SubItems[0].Text)));
                                m_iParentLeft--;
                            }
                        }
                        else
                        {
                            deleteFile(Path.Combine(txtPathLeft.Text, item.SubItems[0].Text));
                            m_iParentLeft--;
                        }
                    }

                    setStatus(m_iParentLeft, listViewLeft);
                    m_LeftList.Clear();
                }
            }
        }
        private void createFromLeft()
        {
            createDirectory(m_iParentLeft, listViewLeft, txtPathLeft);
            if (m_LeftList.Count != 0)
                m_LeftList.Clear();
        }
        private void renameFromLeft()
        {
            rename(m_iParentLeft, listViewLeft, txtPathLeft);
            if (m_LeftList.Count != 0)
                m_LeftList.Clear();
        }
        // ==================================================================================

        private void copyFile(string strSource, string strDestination)
        {
            try
            {
                File.Copy(strSource, strDestination);
            }
            catch (System.UnauthorizedAccessException)
            {
                MessageBox.Show("Access deny", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            catch (System.IO.IOException)
            {
                MessageBox.Show("Can not copy! File already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void moveFile(string strSource, string strDestination)
        {
            try
            {
                File.Move(strSource, strDestination);
            }
            catch (System.UnauthorizedAccessException)
            {
                m_bFag = false;
                MessageBox.Show("Access deny", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.IO.IOException)
            {
                m_bFag = false;
                MessageBox.Show("Can not move! File already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void deleteFile(string strPath)
        {
            try
            {
                File.Delete(strPath);
            }
            catch (System.UnauthorizedAccessException)
            {
                MessageBox.Show("Access deny", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        public void moveDirectory(string strSourceDir, string strDestDir)
        {
            try
            {
                if (Directory.Exists(strSourceDir))
                {
                    if (Directory.GetDirectoryRoot(strSourceDir) == Directory.GetDirectoryRoot(strDestDir))
                        Directory.Move(strSourceDir, strDestDir);
                    else
                    {
                        if (listViewLeft.Focused == false) // khong la ben trai thi kiem tra o ben trai
                        {
                            DirectoryInfo[] arrDir = new DirectoryInfo(txtPathLeft.Text).GetDirectories();
                            foreach (DirectoryInfo dir in arrDir)
                                if (dir.Name == new DirectoryInfo(strSourceDir).Name)
                                {
                                    m_bFag = false;
                                    MessageBox.Show("Can not move! Folder already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }
                        }
                        if (listViewRight.Focused == false)
                        {
                            DirectoryInfo[] arrDir = new DirectoryInfo(txtPathRight.Text).GetDirectories();
                            foreach (DirectoryInfo dir in arrDir)
                                if (dir.Name == new DirectoryInfo(strSourceDir).Name)
                                {
                                    m_bFag = false;
                                    MessageBox.Show("Can not move! Folder already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }
                        }
                        copyDirectory(new DirectoryInfo(strSourceDir), new DirectoryInfo(strDestDir));
                    }
                }
            }
            catch (System.UnauthorizedAccessException)
            {
                m_bFag = false;
                MessageBox.Show("Access deny", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.IO.IOException)
            {
                m_bFag = false;
                MessageBox.Show("File already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void copyDirectory(DirectoryInfo diSource, DirectoryInfo diDestination)
        {
            try
            {
                if (!diDestination.Exists)
                    diDestination.Create();

                FileInfo[] arrSrcFiles = diSource.GetFiles();
                foreach (FileInfo fiSrcFile in arrSrcFiles)
                {
                    fiSrcFile.CopyTo(Path.Combine(diDestination.FullName, fiSrcFile.Name));
                }
                DirectoryInfo[] arrDirectories = diSource.GetDirectories();
                foreach (DirectoryInfo diSrcDirectory in arrDirectories)
                {
                    copyDirectory(diSrcDirectory, new DirectoryInfo(Path.Combine(diDestination.FullName, diSrcDirectory.Name)));
                }
            }
            catch (System.UnauthorizedAccessException)
            {
                m_bFag = false;
                MessageBox.Show("Access deny", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.IO.IOException)
            {
                m_bFag = false;
                MessageBox.Show("File or Folder already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void deleteDirectory(DirectoryInfo di)
        {
            try
            {
                if (di.Exists)
                {
                    FileInfo[] arrFile = di.GetFiles();
                    foreach (FileInfo file in arrFile)
                    {
                        file.Delete();
                    }

                    DirectoryInfo[] arrDirectory = di.GetDirectories();
                    foreach (DirectoryInfo diretory in arrDirectory)
                        deleteDirectory(diretory);
                    di.Delete();
                }
            }
            catch (System.UnauthorizedAccessException)
            {
                m_bFag = false;
                MessageBox.Show("Access deny", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.IO.IOException)
            {
                m_bFag = false;
                MessageBox.Show("Access deny", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void moveFolder(string strSource, string strDestination)
        {
            if (strSource == strDestination)
                MessageBox.Show("Can not move! The source and the destination must be different", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
            {
                moveDirectory(strSource, strDestination);
                if (m_bFag == true)
                    deleteDirectory(new DirectoryInfo(strSource));

            }
        }

        private void setStatus(int iParent, ListView listViewParent)
        {
            if (iParent < 0)
                iParent = 0;
            if (m_iIndexLeft < 0)
                m_iIndexLeft = 0;
            if (m_iIndexRight < 0)
                m_iIndexRight = 0;

            displayDirectory(txtPathLeft.Text, listViewLeft, imageListLeft, m_iIndexLeft, txtPathLeft, toolStripStatusLabelLeft);
            displayDirectory(txtPathRight.Text, listViewRight, imageListRight, m_iIndexRight, txtPathRight, toolStripStatusLabelRight);

            if (m_iControlLeft == 0) // co bam Ctrl A
            {
                listViewLeft.Items[0].Focused = true;
                listViewLeft.Items[0].Selected = true;
                return;
            }
            if (m_iControlRight == 0)
            {
                listViewRight.Items[0].Focused = true;
                listViewRight.Items[0].Selected = true;
                return;
            }

            if (iParent < listViewParent.Items.Count)
            {
                listViewParent.Items[iParent].Focused = true;
                listViewParent.Items[iParent].Selected = true;
                return;
            }
            else
            {
                if (iParent >= listViewParent.Items.Count)
                    iParent = listViewParent.Items.Count - 1;
                if (iParent > 0)
                {
                    listViewParent.Items[iParent - 1].Focused = true;
                    listViewParent.Items[iParent - 1].Selected = true;
                }

            }

        }

        private void copyFolder(string strSource, string strDestination)
        {
            if (strSource == strDestination)
                MessageBox.Show("Can not copy! The source and the destination must be different", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
            {
                if (listViewLeft.Focused == false) // khong la ben trai thi kiem tra o ben trai
                {
                    DirectoryInfo[] arrDir = new DirectoryInfo(txtPathLeft.Text).GetDirectories();
                    foreach (DirectoryInfo dir in arrDir)
                        if (dir.Name == new DirectoryInfo(strSource).Name)
                        {
                            MessageBox.Show("Can not copy! Folder already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                }
                if (listViewRight.Focused == false)
                {
                    DirectoryInfo[] arrDir = new DirectoryInfo(txtPathRight.Text).GetDirectories();
                    foreach (DirectoryInfo dir in arrDir)
                        if (dir.Name == new DirectoryInfo(strSource).Name)
                        {
                            MessageBox.Show("Can not copy! Folder already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                }

                copyDirectory(new DirectoryInfo(strSource), new DirectoryInfo(strDestination));
            }
        }

        private double countSize(DirectoryInfo dir)
        {
            double Size = 0;
            FileInfo[] arrFile = dir.GetFiles();
            foreach (FileInfo file in arrFile)
            {
                Size += file.Length;
            }
            DirectoryInfo[] arrDir = dir.GetDirectories();
            foreach (DirectoryInfo di in arrDir)
            {
                Size += countSize(di);
            }
            return (Size);
        }

        private void createDirectory(int iParent, ListView listViewParent, TextBox textBoxParent)
        {
            frmNewDirectory dlg = new frmNewDirectory();
            dlg.ShowDialog();

            dlg.Focus();
            if (dlg.DialogResult == DialogResult.OK)
            {
                string strDirName = dlg.getName();

                if (strDirName == "")
                {
                    MessageBox.Show("Can not create directory! The directory name is empy!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                DirectoryInfo[] arrDir = new DirectoryInfo(textBoxParent.Text).GetDirectories();
                foreach (DirectoryInfo dir in arrDir)
                {
                    if (strDirName == dir.Name)
                    {
                        MessageBox.Show("Can not create directory! The directory name already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                try
                {
                    System.IO.Directory.CreateDirectory(Path.Combine(textBoxParent.Text, strDirName));

                    setStatus(iParent, listViewParent);
                    ListViewItem item = listViewParent.FindItemWithText(strDirName);
                    iParent = listViewParent.Items.IndexOf(item);
                    setStatus(iParent, listViewParent);
                }
                catch (System.IO.IOException)
                {
                    MessageBox.Show("Access deny", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void rename(int iParent, ListView listViewParent, TextBox textBoxParent)
        {
            iParent = listViewParent.SelectedIndices[0];

            frmRenameDirectory dlg = new frmRenameDirectory();
            dlg.ShowDialog();

            dlg.Focus();

            if (dlg.DialogResult == DialogResult.OK)
            {
                string strNewName = dlg.getNewName();
                if (strNewName == "")
                {
                    MessageBox.Show("Can not rename! The new name is empy!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (listViewParent.FocusedItem.SubItems[2].Text == "Dir")
                {
                    DirectoryInfo[] arrDir = new DirectoryInfo(textBoxParent.Text).GetDirectories();
                    foreach (DirectoryInfo dir in arrDir)
                    {
                        if (strNewName == dir.Name)
                        {
                            MessageBox.Show("Can not rename! The directory name already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    try
                    {
                        System.IO.Directory.Move(Path.Combine(textBoxParent.Text, listViewParent.FocusedItem.SubItems[0].Text), Path.Combine(textBoxParent.Text, strNewName));
                        setStatus(iParent, listViewParent);
                    }
                    catch (System.IO.IOException)
                    {
                        MessageBox.Show("Access deny", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    FileInfo[] arrAllFile = new DirectoryInfo(textBoxParent.Text).GetFiles();
                    foreach (FileInfo file in arrAllFile)
                    {
                        if (strNewName == file.Name)
                        {
                            MessageBox.Show("Can not rename! The file name already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    try
                    {
                        System.IO.File.Move(Path.Combine(textBoxParent.Text, listViewParent.FocusedItem.SubItems[0].Text), Path.Combine(textBoxParent.Text, strNewName));
                        setStatus(iParent, listViewParent);
                    }
                    catch (System.UnauthorizedAccessException)
                    {
                        MessageBox.Show("Access deny", "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                }
            }
        }

        private string countSub(DirectoryInfo dir)
        {
            double dSubFile = 0;
            double dSubDir = 0;

            DirectoryInfo[] arrDir = dir.GetDirectories();
            dSubDir = arrDir.Count();

            FileInfo[] arrFile = dir.GetFiles();
            dSubFile = arrFile.Count();

            string strResult = dSubDir.ToString() + " Dir(s) / " + dSubFile.ToString() + " File(s)";
            return strResult;
        }


        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listViewLeft.Focused == true)
                copyFromLefttToRight();
            else
                if (listViewRight.Focused == true)
                    copyFromRightToLeft();
                else
                    return;
        }

        private void moveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listViewLeft.Focused == true)
                moveFromLeftToRight();
            else
                if (listViewRight.Focused == true)
                    moveFromRightToLeft();
                else
                    return;
        }

        private void createFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listViewLeft.Focused == true)
                createFromLeft();
            else
                if (listViewRight.Focused == true)
                    createFromRight();
                else
                    return;
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listViewLeft.Focused == true)
                deleteFromLeft();
            else
                if (listViewRight.Focused == true)
                    deleteFromRight();
                else
                    return;
        }

        private void renameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listViewLeft.Focused == true)
                renameFromLeft();
            else
                if (listViewRight.Focused == true)
                    renameFromRight();
                else
                    return;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Programming by Pham Hoai Vu and Nguyen Quang Anh", "CopyRight", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private UserData Login()
        {
            frmLogin frm = new frmLogin();
            UserData userRet = null;
            if (frm.ShowDialog(this) == DialogResult.OK)
            {
                userRet = m_userManager.LoginByEmail(frm.Email, frm.Passphrase);
                if (userRet != null)
                {
                    frmMain.sEmail = frm.Email;
                    frmMain.sPassphrase = frm.Passphrase;
                    MessageBox.Show("Login Successful!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    this.encryptToolStripMenuItem.Enabled = true;
                    this.encryptWithToolStripMenuItem1.Enabled = true;
                }
                else
                {
                    MessageBox.Show("Login Failed! Wrong Passphrase", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                
            }
            return userRet;
        }

        private void updateMenu(bool b)
        {
            this.decryptToolStripMenuItem.Enabled = b;
            this.decrpytWithToolStripMenuItem.Enabled = b;

            this.toolStripMenuItemEncrypt.Enabled = b;
            this.toolStripMenuItemEncryptWith.Enabled = b;

            this.toolStripMenuItemVerifySignature.Enabled = b;
            this.verifySignatureToolStripMenuItem1.Enabled = b;

            this.toolStripMenuItemDigitalSign.Enabled = b;
            this.digitalSignToolStripMenuItem.Enabled = b;
        }

        private void digitalSignToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int iParent = 0;
            ListView lList = null;

            string currentDir = string.Empty;
            string globalPath = string.Empty;

            if (listViewLeft.Focused == true)
            {
                iParent = m_iParentLeft;
                lList = listViewLeft;
                currentDir = txtPathLeft.Text;
            }
            else
                if (listViewRight.Focused == true)
                {
                    iParent = m_iParentRight;
                    lList = listViewRight;
                    currentDir = txtPathRight.Text;
                }
            if (lList == null)
            {
                MessageBox.Show("You must select a file!", "Info");
                return;
            }
            if (lList.FocusedItem.Text != string.Empty &&
                    lList.FocusedItem.Text.CompareTo("[...]") != 0)
            {
                string sPath = Path.Combine(currentDir, lList.FocusedItem.Text);

                if (File.Exists(sPath))
                {
                    if (this.toolStripMenuItemLogin.Text == "Logout")
                    {
                        try
                        {
                            UserData userData = m_userManager.LoginByEmail(frmMain.sEmail, frmMain.sPassphrase);
                            if (userData != null)
                            {
                                try
                                {
                                    Signer.Sign(userData, frmMain.sPassphrase, sPath, getSignFileName(sPath));
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(this, "Error:\r\n" + ex.Message, "Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }
                            }
                            else
                            {
                                MessageBox.Show(this, "This user is not existed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }

                            setStatus(iParent, lList);

                            MessageBox.Show(this, "Successfully!", "Congrats", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(this, string.Format("Error:\r\n{0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }

                }
            }
        }

        public static string getEncryptFileName(string sCurrent, List<string> list)
        {
            string sOutFileName = string.Empty;
            // chi la 1 file
            if (list.Count == 1)
            {
                if (File.Exists(Path.Combine(sCurrent, list[0])))
                {
                    sOutFileName = Path.Combine(sCurrent, list[0]);
                    if (sOutFileName.LastIndexOf(".") == sOutFileName.Length - 4)
                        sOutFileName = sOutFileName.Substring(0, sOutFileName.LastIndexOf(".")) + sENP;
                    else
                        sOutFileName += sENP;
                    return sOutFileName;
                }
                else if (Directory.Exists(Path.Combine(sCurrent, list[0])))
                {
                    sOutFileName = Path.Combine(sCurrent, list[0] + sENP);
                    return sOutFileName;
                }
            }
            int i = sCurrent.LastIndexOf("\\");
            if (i == sCurrent.Length - 1)
                sOutFileName = Path.Combine(sCurrent, sCurrent[0].ToString() + sENP);
            else
                sOutFileName = Path.Combine(sCurrent, sCurrent.Substring(i + 1, sCurrent.Length - i - 1) + sENP);
            return sOutFileName;
        }
        public static string getSignFileName(string sFile)
        {
            string sOutFileName = sFile;
            if (sOutFileName.LastIndexOf(".") == sOutFileName.Length - 4)
                sOutFileName = sOutFileName.Substring(0, sOutFileName.LastIndexOf(".")) + sSIG;
            else
                sOutFileName += sSIG;
            return sOutFileName;
        }
        private void encryptToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string currentDir = string.Empty;
            string selectedItem = string.Empty;

            int iParent = 0;
            ListView lList = null;


            List<string> lstEncryptInputFiles = new List<string>();

            if (listViewLeft.Focused == true)
            {
                currentDir = txtPathLeft.Text;

                foreach (ListViewItem lvi in m_LeftList)
                    if (lvi.SubItems[0].Text.CompareTo("[...]") != 0)
                        lstEncryptInputFiles.Add(lvi.SubItems[0].Text);

                if (lstEncryptInputFiles.Count < 1 &&
                    listViewLeft.SelectedItems.Count > 0 &&
                    listViewLeft.SelectedItems[0].Text != string.Empty &&
                    listViewLeft.SelectedItems[0].Text.CompareTo("[...]") != 0)
                {
                    lstEncryptInputFiles.Add(listViewLeft.SelectedItems[0].Text);
                }
                iParent = m_iParentLeft;
                lList = listViewLeft;
            }
            else
                if (listViewRight.Focused == true)
                {
                    currentDir = txtPathRight.Text;

                    foreach (ListViewItem lvi in m_RightList)
                        if (lvi.SubItems[0].Text.CompareTo("[...]") != 0)
                            lstEncryptInputFiles.Add(lvi.SubItems[0].Text);

                    if (lstEncryptInputFiles.Count < 1 &&
                        listViewRight.SelectedItems.Count > 0 &&
                        listViewRight.SelectedItems[0].Text != string.Empty &&
                        listViewRight.SelectedItems[0].Text.CompareTo("[...]") != 0)
                    {
                        lstEncryptInputFiles.Add(listViewRight.SelectedItems[0].Text);
                    }
                    iParent = m_iParentRight;
                    lList = listViewRight;
                }
            if (lstEncryptInputFiles.Count < 1)
            {
                MessageBox.Show("You must select at least one file or folder!", "Info");
                return;
            }


            ///
            frmEncryptProcess frmp = new frmEncryptProcess();
            frmp.currentDir = currentDir;
            frmp.lstEncryptInputFiles = lstEncryptInputFiles;
            frmp.SymmetricAlgorithms = this.SymmetricAlgorithms;
            frmp.CipherMode = this.CipherMode;
            frmp.PaddingMode = this.PaddingMode;
            frmp.Zip = this.Zip;
            frmp.sEmail = frmMain.sEmail;
            frmp.sFileOutput = frmMain.getEncryptFileName(currentDir, lstEncryptInputFiles);

            if (File.Exists(frmp.sFileOutput))
            {
                MessageBox.Show("Can not encrypt! Destination file already exists\nChoose Encrypt with... to change file name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            frmp.ShowDialog();
       
            // careful!!!
            setStatus(iParent, lList);
            if (m_LeftList.Count != 0)
                m_LeftList.Clear();
            if (m_RightList.Count != 0)
                m_RightList.Clear();
        }

       

        /// <summary>
        /// //////////////
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void decryptToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int iParent = 0;
            ListView lList = null;

            string currentDir = string.Empty;
            string globalPath = string.Empty;

            if (listViewLeft.Focused == true)
            {
                iParent = m_iParentLeft;
                lList = listViewLeft;
                currentDir = txtPathLeft.Text;
            }
            else
                if (listViewRight.Focused == true)
                {
                    iParent = m_iParentRight;
                    lList = listViewRight;
                    currentDir = txtPathRight.Text;
                }
            if (lList == null)
            {
                MessageBox.Show("You must select a encrypted file (" + sENP + ")!", "Info");
                return;
            }
            if (lList.FocusedItem.Text != string.Empty &&
                    lList.FocusedItem.Text.CompareTo("[...]") != 0)
            {
                string sPath = Path.Combine(currentDir, lList.FocusedItem.Text);
               
                ///////////////////////////////////////////////////////////////////////////////
                string sTemp = sPath.Substring(0, sPath.Length - 4);

                if (Directory.Exists(sTemp))
                {
                    MessageBox.Show("Can not decrypt! Destination folder already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (File.Exists(sPath) && sPath.EndsWith(sENP))
                {
                    if (this.toolStripMenuItemLogin.Text == "Logout")
                    {
                        ///////////test
                        try
                        {
                            frmDecryptProcess fdp = new frmDecryptProcess();
                            fdp.outputDir = Path.Combine(currentDir, lList.FocusedItem.Text.Substring(0, lList.FocusedItem.Text.Length - 4));
                            Directory.CreateDirectory(fdp.outputDir);
                            fdp.sFile = sPath;
                            fdp.ShowDialog();
                            setStatus(iParent, lList);
                        }
                        catch (System.Security.Cryptography.CryptographicException)
                        {
                            MessageBox.Show("ERROR", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }

                }
            }
        }

        private void configToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmOption cfg = new frmOption();
            if (cfg.ShowDialog(this) == DialogResult.OK)
            {
                SymmetricAlgorithms = cfg.SymmetricAlgorithms;
                CipherMode = cfg.CipherMode;
                PaddingMode = cfg.PaddingMode;
                Zip = cfg.Zip;
            }
        }

        private void listViewLeft_Click(object sender, EventArgs e)
        {
            if (listViewLeft.FocusedItem.Text != string.Empty &&
                    listViewLeft.FocusedItem.Text.CompareTo("[...]") != 0 && 
                    this.toolStripMenuItemLogin.Text == "Logout")
            {
                
                string sPath = Path.Combine(txtPathLeft.Text, listViewLeft.FocusedItem.Text);

                if (File.Exists(sPath))
                {
                    this.digitalSignToolStripMenuItem.Enabled = true;
                    this.toolStripMenuItemDigitalSign.Enabled = true;

                    this.toolStripMenuItemVerifySignature.Enabled = true;
                    this.verifySignatureToolStripMenuItem1.Enabled = true;

                    if (sPath.EndsWith(sENP))
                    {
                        this.decryptToolStripMenuItem.Enabled = true;
                        this.toolStripMenuItemDecrypt.Enabled = true;
                        this.decrpytWithToolStripMenuItem.Enabled = true;
                        this.toolStripMenuItemDecryptWith.Enabled = true;
                        //this.toolStripMenuItemVerifySignature.Enabled = true;
                        return;
                    }
                    else
                    {
                        this.decryptToolStripMenuItem.Enabled = false;
                        this.toolStripMenuItemDecrypt.Enabled = false;
                        this.decrpytWithToolStripMenuItem.Enabled = false;
                        this.toolStripMenuItemDecryptWith.Enabled = false;
                    }
                    return;
                }
            }
            
            this.decryptToolStripMenuItem.Enabled = false;
            this.toolStripMenuItemDecrypt.Enabled = false;

           

            this.decrpytWithToolStripMenuItem.Enabled = false;
            this.toolStripMenuItemDecryptWith.Enabled = false;

            this.digitalSignToolStripMenuItem.Enabled = false;
            this.toolStripMenuItemDigitalSign.Enabled = false;

            this.toolStripMenuItemVerifySignature.Enabled = false;
            this.verifySignatureToolStripMenuItem1.Enabled = false;
        }

        private void listViewRight_Click(object sender, EventArgs e)
        {
            if (listViewRight.FocusedItem.Text != string.Empty &&
                    listViewRight.FocusedItem.Text.CompareTo("[...]") != 0)
            {
                string sPath = Path.Combine(txtPathRight.Text, listViewRight.FocusedItem.Text);

                if (File.Exists(sPath) && this.toolStripMenuItemLogin.Text == "Logout")
                {
                    this.digitalSignToolStripMenuItem.Enabled = true;
                    this.toolStripMenuItemDigitalSign.Enabled = true;

                    this.toolStripMenuItemVerifySignature.Enabled = true;
                    this.verifySignatureToolStripMenuItem1.Enabled = true;

                    if (sPath.EndsWith(sENP))
                    {
                        this.decryptToolStripMenuItem.Enabled = true;
                        this.toolStripMenuItemDecrypt.Enabled = true;
                        this.decrpytWithToolStripMenuItem.Enabled = true;
                        this.toolStripMenuItemDecryptWith.Enabled = true;
                        //this.toolStripMenuItemVerifySignature.Enabled = true;
                        return;
                    }
                    else
                    {
                        this.decryptToolStripMenuItem.Enabled = false;
                        this.toolStripMenuItemDecrypt.Enabled = false;
                        this.decrpytWithToolStripMenuItem.Enabled = false;
                        this.toolStripMenuItemDecryptWith.Enabled = false;
                    }
                    return;
                }
            }
            this.decryptToolStripMenuItem.Enabled = false;
            this.toolStripMenuItemDecrypt.Enabled = false;



            this.decrpytWithToolStripMenuItem.Enabled = false;
            this.toolStripMenuItemDecryptWith.Enabled = false;

            this.digitalSignToolStripMenuItem.Enabled = false;
            this.toolStripMenuItemDigitalSign.Enabled = false;

            this.toolStripMenuItemVerifySignature.Enabled = false;
            this.verifySignatureToolStripMenuItem1.Enabled = false;
        }

        private void labelNewUser_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            frmNewUser frm = new frmNewUser();
            frm.ShowDialog();
        }

        private void labelUserSetting_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                frmUserSetting frm = new frmUserSetting();
                frm.m_sEmail = frmMain.sEmail;
                frm.ShowDialog();
            }
            catch (Exception)
            {
                MessageBox.Show("You have to login first.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        private void labelLogin_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            LoginGui();
        }

        private void loginToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            LoginGui();
        }

        private void toolStripMenuItemLogin_Click(object sender, EventArgs e)
        {
            LoginGui();
        }

        private void LoginGui()
        {
            if (labelLogin.Text == "Login")
            {
                UserData ud = this.Login();
                if (ud != null)
                {
                    this.loginToolStripMenuItem1.Text = "Logout";
                    this.settingToolStripMenuItem.Enabled = true;
                    this.toolStripMenuItemLogin.Text = "Logout";
                    this.updateMenu(true);

                    this.labelLogin.Text = "Logout";
                    this.labelName.Text = "You are login as " + ud.Name;
                    this.labelUserSetting.Visible = true;
                    this.labelNewUser.Visible = false;

                }
            }
            else if (labelLogin.Text == "Logout")
            {
                DialogResult dr = MessageBox.Show("Do you realy want to logout?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (dr == DialogResult.Yes)
                {
                    frmMain.sEmail = string.Empty;
                    frmMain.sPassphrase = string.Empty;
                    this.loginToolStripMenuItem1.Text = "Login";
                    this.settingToolStripMenuItem.Enabled = false;
                    this.toolStripMenuItemLogin.Text = "Login";
                    this.updateMenu(false);

                    this.labelLogin.Text = "Login";
                    this.labelName.Text = String.Empty;
                    this.labelUserSetting.Visible = false;
                    this.labelNewUser.Visible = true;
                }
            }
        }

        private void settingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                frmUserSetting frm = new frmUserSetting();
                frm.m_sEmail = frmMain.sEmail;
                frm.ShowDialog();
            }
            catch (Exception)
            {
                MessageBox.Show("You have to login first.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void newUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmNewUser frm = new frmNewUser();
            frm.ShowDialog();
        }

        private void userManagementToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmManageUser frm = new frmManageUser();
            frm.ShowDialog();
           
        }

        private void encryptWithToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // get file, folder is chosen
            string currentDir = string.Empty;
            string selectedItem = string.Empty;

            int iParent = 0;
            ListView lList = null;

            
            List<string> lstEncryptInputFiles = new List<string>();

            if (listViewLeft.Focused == true)
            {
                currentDir = txtPathLeft.Text;

                foreach (ListViewItem lvi in m_LeftList)
                    if (lvi.SubItems[0].Text.CompareTo("[...]") != 0)
                        lstEncryptInputFiles.Add(lvi.SubItems[0].Text);

                if (lstEncryptInputFiles.Count < 1 &&
                    listViewLeft.SelectedItems.Count > 0 &&
                    listViewLeft.SelectedItems[0].Text != string.Empty &&
                    listViewLeft.SelectedItems[0].Text.CompareTo("[...]") != 0)
                {
                    lstEncryptInputFiles.Add(listViewLeft.SelectedItems[0].Text);
                }
                iParent = m_iParentLeft;
                lList = listViewLeft;
            }
            else
                if (listViewRight.Focused == true)
                {
                    currentDir = txtPathRight.Text;

                    foreach (ListViewItem lvi in m_RightList)
                        if (lvi.SubItems[0].Text.CompareTo("[...]") != 0)
                            lstEncryptInputFiles.Add(lvi.SubItems[0].Text);

                    if (lstEncryptInputFiles.Count < 1 &&
                        listViewRight.SelectedItems.Count > 0 &&
                        listViewRight.SelectedItems[0].Text != string.Empty &&
                        listViewRight.SelectedItems[0].Text.CompareTo("[...]") != 0)
                    {
                        lstEncryptInputFiles.Add(listViewRight.SelectedItems[0].Text);
                    }
                    iParent = m_iParentRight;
                    lList = listViewRight;
                }
            if (lstEncryptInputFiles.Count < 1)
            {
                MessageBox.Show("You must select at least one file or folder!", "Info");
                return;
            }

            // show encrypt option
            frmEncryptOption frm = new frmEncryptOption();
            frm.sFileOutput = frmMain.getEncryptFileName(currentDir, lstEncryptInputFiles);

            // control ZIP option
            if (lstEncryptInputFiles.Count > 1)
                frm.canZip = false;
            else
                frm.canZip = true;

            if (frm.ShowDialog() == DialogResult.OK)
            {
                frmEncryptProcess frmp = new frmEncryptProcess();
                frmp.currentDir = currentDir;
                frmp.lstEncryptInputFiles = lstEncryptInputFiles;
                frmp.SymmetricAlgorithms = frm.SymmetricAlgorithms;
                frmp.CipherMode = frm.CipherMode;
                frmp.PaddingMode = frm.PaddingMode;
                frmp.Zip = frm.Zip;
                frmp.sEmail = frm.sEmail;
                frmp.sFileOutput = frm.sFileOutput;


                frmp.ShowDialog();

                // careful!!!
                setStatus(iParent, lList);
                if (m_LeftList.Count != 0)
                    m_LeftList.Clear();
                if (m_RightList.Count != 0)
                    m_RightList.Clear();
            }
            else
            {
                // careful!!!
                setStatus(iParent, lList);
                if (m_LeftList.Count != 0)
                    m_LeftList.Clear();
                if (m_RightList.Count != 0)
                    m_RightList.Clear();
            }
        }

        private void decrpytWithToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int iParent = 0;
            ListView lList = null;

            string currentDir = string.Empty;
            string globalPath = string.Empty;

            if (listViewLeft.Focused == true)
            {
                iParent = m_iParentLeft;
                lList = listViewLeft;
                currentDir = txtPathLeft.Text;
            }
            else
                if (listViewRight.Focused == true)
                {
                    iParent = m_iParentRight;
                    lList = listViewRight;
                    currentDir = txtPathRight.Text;
                }
            if (lList == null)
            {
                MessageBox.Show("You must select a encrypted file (" + sENP + ")!", "Info");
                return;
            }
            if (lList.FocusedItem.Text != string.Empty &&
                    lList.FocusedItem.Text.CompareTo("[...]") != 0)
            {
                string sPath = Path.Combine(currentDir, lList.FocusedItem.Text);

                if (File.Exists(sPath) && sPath.EndsWith(sENP))
                {
                    if (this.toolStripMenuItemLogin.Text == "Logout")
                    {
                        frmDecryptOption fdo = new frmDecryptOption();
                        fdo.sOutputDir = Path.Combine(currentDir, lList.FocusedItem.Text.Substring(0, lList.FocusedItem.Text.Length - 4));

                        if (fdo.ShowDialog() == DialogResult.OK)
                        {
                            frmDecryptProcess fdp = new frmDecryptProcess();
                            fdp.outputDir = fdo.sOutputDir;

                            if (Directory.Exists(fdp.outputDir))
                            {
                                MessageBox.Show("Can not decrypt! Destination folder already exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }

                            Directory.CreateDirectory(fdp.outputDir);
                            fdp.sFile = sPath;
                            fdp.ShowDialog();
                            setStatus(iParent, lList);
                        }
                    }
                }
            }
        }

        private void toolStripMenuItemVerifySignature_Click(object sender, EventArgs e)
        {
            frmVerifySignature frm = new frmVerifySignature();
            frm.ShowDialog();
        }
    }
}
